/**
 *
 */
package com.javademos.train.dynamicdatasource.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.javademos.train.dynamicdatasource.entity.DemoEntity;


@Component
public class DemoDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 不指定数据源使用默认数据源
     *
     * @return
     */

    public List<DemoEntity> getList() {
        String sql = "select * from demo_entity";
        return (List<DemoEntity>) jdbcTemplate.query(sql, new RowMapper<DemoEntity>() {
            @Override
            public DemoEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
                DemoEntity demoEntity = new DemoEntity();
                demoEntity.setId(rs.getLong("id"));
                demoEntity.setName(rs.getString("name"));
                return demoEntity;
            }
        });
    }

    public DemoEntity findOne(Long id) {
        String sql = "select * from demo_entity where id = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{id},
                    new BeanPropertyRowMapper<DemoEntity>(DemoEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }
}
